package com.demo.search.util;

import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;

/**
 * 检索的语法分析器工具类
 * 
 * @author ryuu.kk
 * 
 */
public abstract class AnalyzerUtils {

	/**
	 * 使用分析器对指定的字符串进行分析后,
	 * 显示语汇单元的字符属性、偏移量属性、位置向量、类型等信息
	 * @param analyzer Analyzer
	 * @param text String
	 * @throws IOException
	 */
	public static void displayTokens(Analyzer analyzer, String text)
			throws IOException {
		displayTokens(analyzer.tokenStream("contens", new StringReader(text)));
	}

	/**
	 * 根据语汇单元显示字符属性、偏移量属性、位置向量、类型等信息
	 * @param stream TokenStream
	 * @throws IOException
	 */
	public static void displayTokens(TokenStream stream) throws IOException {
		// 字符属性
		CharTermAttribute term = stream.addAttribute(CharTermAttribute.class);
		// 偏移量属性
		OffsetAttribute offset = stream.addAttribute(OffsetAttribute.class);
		// 位置向量属性
		PositionIncrementAttribute posIncr = stream
				.addAttribute(PositionIncrementAttribute.class);
		// 类型属性
		TypeAttribute type = stream.addAttribute(TypeAttribute.class);

		int position = 0;
		while (stream.incrementToken()) {
			// 打印分析的字符
			System.out.print("[" + term.toString() + "]");
			int increment = posIncr.getPositionIncrement();
			if (increment > 0) {
				position += increment;
				System.out.print("\n" + position + ":");
			}
			System.out.print("[" + term.toString() + ":" + offset.startOffset()
					+ "->" + offset.endOffset() + ":" + type.type() + "]");
		}
	}
}
